package com.cskaoyan.service.impl;

import com.cskaoyan.bean.WxOrderBaseData;
import com.cskaoyan.bean.bo.WxOrderGoodsCommentBO;
import com.cskaoyan.bean.bo.WxOrderIdBO;
import com.cskaoyan.bean.bo.WxOrderListBO;
import com.cskaoyan.bean.bo.WxOrderSubmitBO;
import com.cskaoyan.bean.pojo.*;
import com.cskaoyan.bean.vo.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.service.WxOrderService;
import com.cskaoyan.util.CurrentUesr;
import com.cskaoyan.util.MySystemUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author JJ
 * @description WxOrderService的实现类
 * @time 2021/7/11 22:39
 */
@Service
public class WxOrderServiceImpl implements WxOrderService {

    @Autowired
    MallOrderMapper mallOrderMapper;

    @Autowired
    MallOrderGoodsMapper mallOrderGoodsMapper;

    @Autowired
    MallCartMapper mallCartMapper;

    @Autowired
    MallAddressMapper mallAddressMapper;

    @Autowired
    MallCouponMapper mallCouponMapper;

    @Autowired
    MallCommentMapper mallCommentMapper;


    @Autowired
    MallGoodsProductMapper mallGoodsProductMapper;


    @Autowired
    MallCouponUserMapper mallCouponUserMapper;


    @Autowired
    MySystemUtil mySystemUtil;



    @Override
    public WxOrderBaseData<WxOrderDataBeanVO> getListByWx(WxOrderListBO listBO) {

        //执行查询之前写一行代码即可
        PageHelper.startPage(listBO.getPage(), listBO.getSize());

        //工具类获取当前用户id
        Integer userId = CurrentUesr.getUserId();


        MallOrderExample mallOrderExample = new MallOrderExample();
        MallOrderExample.Criteria MallOrderExamplecriteria = mallOrderExample.createCriteria();


        MallOrderGoodsExample mallOrderGoodsExample = new MallOrderGoodsExample();
        MallOrderGoodsExample.Criteria MallOrderGoodsExamplecriteria = mallOrderGoodsExample.createCriteria();


        //只显示未被删除的订单
        MallOrderExamplecriteria.andDeletedEqualTo(false);
        MallOrderExamplecriteria.andUserIdEqualTo(userId);

        List<WxOrderDataBeanVO> wxOrderDataBeanVOList = new LinkedList<>();
//        WxOrderDataBeanVO wxOrderDataBeanVO = new WxOrderDataBeanVO();


        if (listBO.getShowType() != null && listBO.getShowType() == 1) {
            //1代表未付款，对应状态码为101,设置对应的handleOption
            MallOrderExamplecriteria.andOrderStatusEqualTo(101);


        }
        if (listBO.getShowType() != null && listBO.getShowType() == 2) {
            //2代表已付款，对应状态码为201,设置对应的handleOption
            MallOrderExamplecriteria.andOrderStatusEqualTo(201);

        }
        if (listBO.getShowType() != null && listBO.getShowType() == 3) {
            //3代表已发货，对应状态码为301,设置对应的handleOption
            MallOrderExamplecriteria.andOrderStatusEqualTo(301);

        }
        if (listBO.getShowType() != null && listBO.getShowType() == 4) {
            //4代表已收货，待评价，对应状态码为401,设置对应的handleOption

            List<Short> shorts = new ArrayList<>();
            shorts.add(Short.parseShort("401"));
            shorts.add(Short.parseShort("402"));

            MallOrderExamplecriteria.andOrderStatusIn(shorts);
//            MallOrderExamplecriteria.andOrderStatusEqualTo(401);
            MallOrderExamplecriteria.andCommentsGreaterThan(Short.parseShort("0"));
            //todo 加个402？

        }
        if (listBO.getShowType() == null || listBO.getShowType() == 0) {
            //显示所有订单的逻辑有七种状态！！！

        }

        //订单排序直接写死即可
        mallOrderExample.setOrderByClause("add_time"+ " " + "desc");



        List<MallOrder> mallOrders = mallOrderMapper.selectByExample(mallOrderExample);



        //-------------------------
        // todo
        //设置自动过期检测
        //未付款超过时间变为系统取消,未收货变为系统收货，未评价变为不许评价
        Date date = new Date();

//-------------------------



        Integer count = 0;
        Integer page = 0;
        //获取订单里的所有订单id 并加入到每一个WxOrderDataBeanVO中
//        List<Integer> ids=new LinkedList<>();
        for (MallOrder mallOrder : mallOrders) {


            //-------------------------
            //系统取消设置
            if (mallOrder.getOrderStatus()==101){
                Date addTime = mallOrder.getAddTime();

                Calendar calendar = Calendar.getInstance();

                //根据后台配置，获得配置时间
                Map<String, String> systemMap = mySystemUtil.systemMap();
                Integer orderUnpaidTime = Integer.parseInt(systemMap.get("cskaoyan_mall_order_unpaid"));

                //将创建订单的时间加上配置分钟得到未付款极限时间
                calendar.setTime(addTime);
                calendar.add(Calendar.MINUTE,orderUnpaidTime);
                Date deadline = calendar.getTime();

                //如果现在时间超过deadline就更改为系统取消
                if(date.compareTo(deadline)>0){
                    mallOrder.setUpdateTime(date);
                    mallOrder.setOrderStatus(103);
                    mallOrderMapper.updateByPrimaryKeySelective(mallOrder);
                }
            }

            //系统收货设置
            if (mallOrder.getOrderStatus()==301){
                Date shipTime = mallOrder.getShipTime();

                Calendar calendar = Calendar.getInstance();

                //根据后台配置，获得配置未收货极限时间
                Map<String, String> systemMap = mySystemUtil.systemMap();
                Integer orderUnconfirmTime = Integer.parseInt(systemMap.get("cskaoyan_mall_order_unconfirm"));

                //将发货的时间加上配置天数得到未收货极限时间
                calendar.setTime(shipTime);
                calendar.add(Calendar.DATE,orderUnconfirmTime);
                Date deadline = calendar.getTime();

                //如果现在时间超过deadline就更改为系统收货
                if(date.compareTo(deadline)>0) {
                    mallOrder.setUpdateTime(date);
                    mallOrder.setOrderStatus(402);
                    mallOrder.setConfirmTime(date);//todo 此时也设置为用户确认身份时间
                    mallOrderMapper.updateByPrimaryKeySelective(mallOrder);
                }
            }






            //-------------------------


            count++;
//            ids.add(mallOrder.getId());
            WxOrderDataBeanVO wxOrderDataBeanVO = new WxOrderDataBeanVO();

            //获得订单表id
            Integer id = mallOrder.getId();
            wxOrderDataBeanVO.setId(id);
            //没有团购
            wxOrderDataBeanVO.setGroupin(false);
            //获得实际价格
            BigDecimal actualPrice = mallOrder.getActualPrice();
            wxOrderDataBeanVO.setActualPrice(actualPrice);
            //获得订单编号
            String orderSn = mallOrder.getOrderSn();
            wxOrderDataBeanVO.setOrderSn(orderSn);

            Integer orderStatus = mallOrder.getOrderStatus();
            if (orderStatus != null && orderStatus == 101) {
                //此逻辑应该在从数据库取出状态id后根据九种情况来赋值
                wxOrderDataBeanVO.setOrderStatusText("未付款");
                WxOrderHandleOptionBeanVO wxOrderHandleOptionBeanVO = new WxOrderHandleOptionBeanVO(true, false, true, false, false, false, false);
                wxOrderDataBeanVO.setHandleOption(wxOrderHandleOptionBeanVO);

            } else if (orderStatus != null && orderStatus == 102) {
                wxOrderDataBeanVO.setOrderStatusText("已取消");
                WxOrderHandleOptionBeanVO wxOrderHandleOptionBeanVO = new WxOrderHandleOptionBeanVO(false, true, false, false, false, false, false);
                wxOrderDataBeanVO.setHandleOption(wxOrderHandleOptionBeanVO);

            } else if (orderStatus != null && orderStatus == 103) {
                wxOrderDataBeanVO.setOrderStatusText("已取消(系统)");
                WxOrderHandleOptionBeanVO wxOrderHandleOptionBeanVO = new WxOrderHandleOptionBeanVO(false, true, false, false, false, false, false);
                wxOrderDataBeanVO.setHandleOption(wxOrderHandleOptionBeanVO);

            } else if (orderStatus != null && orderStatus == 201) {
                wxOrderDataBeanVO.setOrderStatusText("已付款");
                WxOrderHandleOptionBeanVO wxOrderHandleOptionBeanVO = new WxOrderHandleOptionBeanVO(false, false, false, false, false, true, false);
                wxOrderDataBeanVO.setHandleOption(wxOrderHandleOptionBeanVO);

            } else if (orderStatus != null && orderStatus == 202) {
                wxOrderDataBeanVO.setOrderStatusText("订单取消，退款中");
                WxOrderHandleOptionBeanVO wxOrderHandleOptionBeanVO = new WxOrderHandleOptionBeanVO(false, false, false, false, false, false, false);
                wxOrderDataBeanVO.setHandleOption(wxOrderHandleOptionBeanVO);

            } else if (orderStatus != null && orderStatus == 203) {
                wxOrderDataBeanVO.setOrderStatusText("已退款");
                WxOrderHandleOptionBeanVO wxOrderHandleOptionBeanVO = new WxOrderHandleOptionBeanVO(false, true, false, false, false, false, false);
                wxOrderDataBeanVO.setHandleOption(wxOrderHandleOptionBeanVO);

            } else if (orderStatus != null && orderStatus == 301) {
                wxOrderDataBeanVO.setOrderStatusText("已发货");
                WxOrderHandleOptionBeanVO wxOrderHandleOptionBeanVO = new WxOrderHandleOptionBeanVO(false, false, false, false, true, false, false);
                wxOrderDataBeanVO.setHandleOption(wxOrderHandleOptionBeanVO);

            } else if (orderStatus != null && orderStatus == 401) {
                wxOrderDataBeanVO.setOrderStatusText("已收货");
                WxOrderHandleOptionBeanVO wxOrderHandleOptionBeanVO = new WxOrderHandleOptionBeanVO(false, true, false, true, false, false, true);
                wxOrderDataBeanVO.setHandleOption(wxOrderHandleOptionBeanVO);
            } else if (orderStatus != null && orderStatus == 402) {
                wxOrderDataBeanVO.setOrderStatusText("已收货(系统)");
                WxOrderHandleOptionBeanVO wxOrderHandleOptionBeanVO = new WxOrderHandleOptionBeanVO(false, true, false, true, false, false, true);
                wxOrderDataBeanVO.setHandleOption(wxOrderHandleOptionBeanVO);

            }

            //每次新的查询必须建立新的example！！！
            MallOrderGoodsExample mallOrderGoodsExample1 = new MallOrderGoodsExample();
            MallOrderGoodsExample.Criteria MallOrderGoodsExamplecriteria1 = mallOrderGoodsExample1.createCriteria();

            //只显示未被删除的
            MallOrderGoodsExamplecriteria1.andDeletedEqualTo(false);

            //根据订单表的订单id去订单商品表里找对应的商品信息
            MallOrderGoodsExamplecriteria1.andOrderIdEqualTo(id);
            List<MallOrderGoods> mallOrderGoods = mallOrderGoodsMapper.selectByExample(mallOrderGoodsExample1);

            //mallOrderGoods中其实是一个订单中的每种商品对应一条信息
            //将取出的数据循环放入   或直接将此bean返回作为goodsList(此bean已经确定故此方案不行)
            List<WxOrderGoodsListBeanVO> wxOrderGoodsListBeanVOS = new LinkedList<>();
            for (MallOrderGoods mallOrderGood : mallOrderGoods) {
                WxOrderGoodsListBeanVO wxOrderGoodsListBeanVO = new WxOrderGoodsListBeanVO(mallOrderGood.getNumber(), mallOrderGood.getPicUrl(), mallOrderGood.getId(), mallOrderGood.getGoodsName());
                wxOrderGoodsListBeanVOS.add(wxOrderGoodsListBeanVO);


                //系统不许评价设置
                if (mallOrder.getOrderStatus()==401||mallOrder.getOrderStatus()==402){
                    Date confirmTime = mallOrder.getConfirmTime();

                    Calendar calendar = Calendar.getInstance();

                    //根据后台配置，获得配置未评价极限时间
                    Map<String, String> systemMap = mySystemUtil.systemMap();
                    Integer orderCommentTime = Integer.parseInt(systemMap.get("cskaoyan_mall_order_comment"));

                    //将确认收货的时间加上配置天数得到未评价极限时间
                    calendar.setTime(confirmTime);
                    calendar.add(Calendar.DATE,orderCommentTime);
                    Date deadline = calendar.getTime();

                    //如果现在时间超过deadline就更改为不许评价
                    if(date.compareTo(deadline)>0) {
                        mallOrderGood.setUpdateTime(date);
                        mallOrderGood.setComment(-1);
                        mallOrderGoodsMapper.updateByPrimaryKeySelective(mallOrderGood);
                    }
                }





            }
            wxOrderDataBeanVO.setGoodsList(wxOrderGoodsListBeanVOS);

            //每一个WxOrderDataBeanVO封装完毕
            wxOrderDataBeanVOList.add(wxOrderDataBeanVO);

            //通过订单id去订单商品表里找对应的商品信息
//            MallOrderGoodsExamplecriteria.andOrderIdIn(ids);
//            List<MallOrderGoods> mallOrderGoods = mallOrderGoodsMapper.selectByExample(mallOrderGoodsExample);
//
//            //将取出的数据循环放入   或直接将此bean返回作为goodsList(此bean已经确定故此方案不行)
//            List<WxOrderGoodsListBeanVO> wxOrderGoodsListBeanVOS = new LinkedList<>();
//            for (MallOrderGoods mallOrderGood : mallOrderGoods) {
//                WxOrderGoodsListBeanVO wxOrderGoodsListBeanVO=new WxOrderGoodsListBeanVO(mallOrderGood.getNumber(),mallOrderGood.getPicUrl(),mallOrderGood.getId(),mallOrderGood.getGoodsName());
//                wxOrderGoodsListBeanVOS.add(wxOrderGoodsListBeanVO);
//            }

        }

        //原来的返回
      /*  WxOrderDataBeanXVO wxOrderDataBeanXVO = new WxOrderDataBeanXVO();
        wxOrderDataBeanXVO.setData(wxOrderDataBeanVOList);
        wxOrderDataBeanXVO.setCount(count);
        wxOrderDataBeanXVO.setTotalPages(count / 10 + 1);

        WxOrderListVO wxOrderListVO = new WxOrderListVO();
        wxOrderListVO.setData(wxOrderDataBeanXVO);

                return wxOrderDataBeanXVO;*/

        //total可以使用countByExample，也可以使用PageHelper来获得
        //int total = mallCouponMapper.countByExample(mallCouponExample);
        //在执行查询之后可以获得分页信息,将查询结果放入PageInfo的构造方法里
        PageInfo<WxOrderDataBeanVO> pageInfo = new PageInfo<>(wxOrderDataBeanVOList);
         count = (int) pageInfo.getTotal();


        return WxOrderBaseData.ok(wxOrderDataBeanVOList, count,count / 10 + 1);



    }


    @Override
    public WxOrderDetailVO getDetailByWx(Integer orderId) {

        MallOrderExample mallOrderExample = new MallOrderExample();
        MallOrderExample.Criteria MallOrderExamplecriteria = mallOrderExample.createCriteria();

        MallOrderGoodsExample mallOrderGoodsExample = new MallOrderGoodsExample();
        MallOrderGoodsExample.Criteria MallOrderGoodsExamplecriteria = mallOrderGoodsExample.createCriteria();


        MallOrder mallOrder = mallOrderMapper.selectByPrimaryKey(orderId);

        MallOrderGoodsExamplecriteria.andOrderIdEqualTo(orderId);
        List<MallOrderGoods> mallOrderGoods = mallOrderGoodsMapper.selectByExample(mallOrderGoodsExample);

        WxOrderDetailVO wxOrderDetailVO = new WxOrderDetailVO();
        wxOrderDetailVO.setOrderGoods(mallOrderGoods);

        WxOrderInfoBeanVO wxOrderInfoBeanVO = new WxOrderInfoBeanVO();

        Integer orderStatus = mallOrder.getOrderStatus();
        if (orderStatus != null && orderStatus == 101) {
            //此逻辑应该在从数据库取出状态id后根据九种情况来赋值
            wxOrderInfoBeanVO.setOrderStatusText("未付款");
            WxOrderHandleOptionBeanVO wxOrderHandleOptionBeanVO = new WxOrderHandleOptionBeanVO(true, false, true, false, false, false, false);
            wxOrderInfoBeanVO.setHandleOption(wxOrderHandleOptionBeanVO);

        } else if (orderStatus != null && orderStatus == 102) {
            wxOrderInfoBeanVO.setOrderStatusText("已取消");
            WxOrderHandleOptionBeanVO wxOrderHandleOptionBeanVO = new WxOrderHandleOptionBeanVO(false, true, false, false, false, false, false);
            wxOrderInfoBeanVO.setHandleOption(wxOrderHandleOptionBeanVO);

        } else if (orderStatus != null && orderStatus == 103) {
            wxOrderInfoBeanVO.setOrderStatusText("已取消(系统)");
            WxOrderHandleOptionBeanVO wxOrderHandleOptionBeanVO = new WxOrderHandleOptionBeanVO(false, true, false, false, false, false, false);
            wxOrderInfoBeanVO.setHandleOption(wxOrderHandleOptionBeanVO);

        } else if (orderStatus != null && orderStatus == 201) {
            wxOrderInfoBeanVO.setOrderStatusText("已付款");
            WxOrderHandleOptionBeanVO wxOrderHandleOptionBeanVO = new WxOrderHandleOptionBeanVO(false, false, false, false, false, true, false);
            wxOrderInfoBeanVO.setHandleOption(wxOrderHandleOptionBeanVO);

        } else if (orderStatus != null && orderStatus == 202) {
            wxOrderInfoBeanVO.setOrderStatusText("订单取消，退款中");
            WxOrderHandleOptionBeanVO wxOrderHandleOptionBeanVO = new WxOrderHandleOptionBeanVO(false, false, false, false, false, false, false);
            wxOrderInfoBeanVO.setHandleOption(wxOrderHandleOptionBeanVO);

        } else if (orderStatus != null && orderStatus == 203) {
            wxOrderInfoBeanVO.setOrderStatusText("已退款");
            WxOrderHandleOptionBeanVO wxOrderHandleOptionBeanVO = new WxOrderHandleOptionBeanVO(false, true, false, false, false, false, false);
            wxOrderInfoBeanVO.setHandleOption(wxOrderHandleOptionBeanVO);

        } else if (orderStatus != null && orderStatus == 301) {
            wxOrderInfoBeanVO.setOrderStatusText("已发货");
            WxOrderHandleOptionBeanVO wxOrderHandleOptionBeanVO = new WxOrderHandleOptionBeanVO(false, false, false, false, true, false, false);
            wxOrderInfoBeanVO.setHandleOption(wxOrderHandleOptionBeanVO);

        } else if (orderStatus != null && orderStatus == 401) {
            wxOrderInfoBeanVO.setOrderStatusText("已收货");
            WxOrderHandleOptionBeanVO wxOrderHandleOptionBeanVO = new WxOrderHandleOptionBeanVO(false, true, false, true, false, false, true);
            wxOrderInfoBeanVO.setHandleOption(wxOrderHandleOptionBeanVO);
        } else if (orderStatus != null && orderStatus == 402) {
            wxOrderInfoBeanVO.setOrderStatusText("已收货(系统)");
            WxOrderHandleOptionBeanVO wxOrderHandleOptionBeanVO = new WxOrderHandleOptionBeanVO(false, true, false, true, false, false, true);
            wxOrderInfoBeanVO.setHandleOption(wxOrderHandleOptionBeanVO);
        }

        //一一赋值封装
        wxOrderInfoBeanVO.setConsignee(mallOrder.getConsignee());
        wxOrderInfoBeanVO.setAddress(mallOrder.getAddress());
        wxOrderInfoBeanVO.setAddTime(mallOrder.getAddTime());
        wxOrderInfoBeanVO.setOrderSn(mallOrder.getOrderSn());
        wxOrderInfoBeanVO.setActualPrice(mallOrder.getActualPrice());
        wxOrderInfoBeanVO.setMobile(mallOrder.getMobile());
        wxOrderInfoBeanVO.setGoodsPrice(mallOrder.getGoodsPrice());
        wxOrderInfoBeanVO.setCouponPrice(mallOrder.getCouponPrice());
        wxOrderInfoBeanVO.setId(mallOrder.getId());
        wxOrderInfoBeanVO.setFreightPrice(mallOrder.getFreightPrice());

        wxOrderDetailVO.setOrderInfo(wxOrderInfoBeanVO);
        return wxOrderDetailVO;
    }

    @Override
    public void prepayByWx(String orderId) {

    }


    @Override
    public Integer submitByWx(WxOrderSubmitBO wxOrderSubmitBO) {

        int userId = CurrentUesr.getUserId();

        Integer addressId = wxOrderSubmitBO.getAddressId();
        Integer cartId = wxOrderSubmitBO.getCartId();
        Integer couponId = wxOrderSubmitBO.getCouponId();

        MallAddress mallAddress = mallAddressMapper.selectByPrimaryKey(addressId);
        //订单id只会传0让你全选
//        MallCart mallCart = mallCartMapper.selectByPrimaryKey(cartId);

        MallCoupon mallCoupon = mallCouponMapper.selectByPrimaryKey(couponId);






        MallOrder mallOrder = new MallOrder();

        mallOrder.setUserId(mallAddress.getUserId());

        Date date = new Date();
        //todo 生成订单号有问题

        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmm");
        String s = sdf.format(date);
        String dateString = s.substring(0, 8);

        Integer i =  date.hashCode();
        String hash = String.valueOf(i);

        String substring = hash.substring(1, 7);

        //通过日期和hash生成订单编号
        mallOrder.setOrderSn(dateString+substring);

        mallOrder.setOrderStatus(101);
        mallOrder.setConsignee(mallAddress.getName());
        mallOrder.setMobile(mallAddress.getMobile());
        mallOrder.setAddress(mallAddress.getAddress());
        mallOrder.setMessage(wxOrderSubmitBO.getMessage());

        // 订单id只会传0让你全选
        MallCartExample mallCartExample = new MallCartExample();
        MallCartExample.Criteria criteria = mallCartExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andCheckedEqualTo(true);
        criteria.andDeletedEqualTo(false);
        //只下单单个商品的时候会传单个的cartId
        if (cartId!=0){
            criteria.andIdEqualTo(cartId);
        }

        List<MallCart> mallCarts = mallCartMapper.selectByExample(mallCartExample);



        //验证货品规格的库存
        for (MallCart mallCart : mallCarts) {
            Integer productId = mallCart.getProductId();
            Short number = mallCart.getNumber();

            MallGoodsProduct mallGoodsProduct = mallGoodsProductMapper.selectByPrimaryKey(productId);
            Integer mallGoodsProductNumber = mallGoodsProduct.getNumber();

            if (number>mallGoodsProductNumber){
                //如果有一个超出就返回-1直接代表下单失败
                return -1;
            }
        }




        //获取商品总价格
        BigDecimal goodsPrice=new BigDecimal("0");
        for (MallCart mallCart : mallCarts) {
            Short num = mallCart.getNumber();
            BigDecimal number = new BigDecimal(num.toString());
            BigDecimal price = mallCart.getPrice();
            goodsPrice=goodsPrice.add(price.multiply(number));
        }

        mallOrder.setGoodsPrice(goodsPrice);

//        //配送费设置
//        BigDecimal freightPrice = new BigDecimal("8");
//        mallOrder.setFreightPrice(freightPrice);
//        if (goodsPrice.doubleValue()>88){
//            mallOrder.setFreightPrice(new BigDecimal("0"));
//        }


        //freightPrice
        //根据后台配置，修改运费
        Map<String, String> systemMap = mySystemUtil.systemMap();
        Double freightMin = Double.parseDouble(systemMap.get("cskaoyan_mall_express_freight_min"));
        Double value = Double.parseDouble(systemMap.get("cskaoyan_mall_express_freight_value"));

        BigDecimal freightPrice = new BigDecimal(systemMap.get("cskaoyan_mall_express_freight_value"));
        if(goodsPrice.doubleValue() < freightMin){
            mallOrder.setFreightPrice(freightPrice);
        }else {
            mallOrder.setFreightPrice(new BigDecimal("0"));
        }





        //优惠券减免 couponId为-1意味着没用优惠券,mallCoupon为空
        BigDecimal discount=new BigDecimal("0");
        mallOrder.setCouponPrice(discount);
        if (couponId!=0&&couponId!=-1){
            discount = mallCoupon.getDiscount();
            mallOrder.setCouponPrice(discount);
        }


        mallOrder.setIntegralPrice(new BigDecimal("0"));//没有用户积分减免
        mallOrder.setGrouponPrice(new BigDecimal("0"));//没有团购优惠价减免

        BigDecimal orderPrice = goodsPrice.add(freightPrice).subtract(discount);


        //如果减免后的总金额小于0也取为0
        if(orderPrice.intValue()<0){
            orderPrice=new BigDecimal("0");
        }
        mallOrder.setOrderPrice(orderPrice);// = goods_price + freight_price - coupon_price

        mallOrder.setActualPrice(orderPrice);// = order_price - integral_price 没有用户积分减免


        mallOrder.setPayId(null);
        mallOrder.setPayTime(null);
        mallOrder.setShipSn(null);
        mallOrder.setShipChannel(null);
        mallOrder.setShipTime(null);

        mallOrder.setConfirmTime(null);
        mallOrder.setComments(null);
        mallOrder.setEndTime(null);
        mallOrder.setAddTime(date);
        mallOrder.setUpdateTime(date);
        mallOrder.setDeleted(false);


        //到这一步才正式开始存入数据到数据库，如果库存不足只要在此之前返回方法即可
        int i1 = mallOrderMapper.insertSelective(mallOrder);
        Integer orderId = mallOrder.getId();

        //被选中的购物车订单中的每一行都要加入到orderGoods表中
        Short goodsNUM=0;
        for (MallCart mallCart : mallCarts) {

        MallOrderGoods mallOrderGoods = new MallOrderGoods();

        mallOrderGoods.setOrderId(orderId);
        mallOrderGoods.setGoodsId(mallCart.getGoodsId());
        mallOrderGoods.setGoodsName(mallCart.getGoodsName());
        mallOrderGoods.setGoodsSn(mallCart.getGoodsSn());
        mallOrderGoods.setProductId(mallCart.getProductId());
        mallOrderGoods.setNumber(mallCart.getNumber());
        mallOrderGoods.setPrice(mallCart.getPrice());
        mallOrderGoods.setSpecifications(mallCart.getSpecifications());
        mallOrderGoods.setPicUrl(mallCart.getPicUrl());
        mallOrderGoods.setComment(null);//todo -1超期不能评价,0可以评价,其他值为用户id
        mallOrderGoods.setAddTime(date);
        mallOrderGoods.setUpdateTime(date);
        mallOrderGoods.setDeleted(false);

        int i2 = mallOrderGoodsMapper.insertSelective(mallOrderGoods);

            goodsNUM++;
        }


        //把comment变为还未评价的商品数量
        mallOrder.setComments(goodsNUM);
        int i3 = mallOrderMapper.updateByPrimaryKeySelective(mallOrder);


        //todo 需要修改的表 货品表 购物车表 优惠券表 积分表？ 一个更新失败会回滚


        //修改货品表
        for (MallCart mallCart : mallCarts) {
            Integer productId = mallCart.getProductId();
            Short number = mallCart.getNumber();

            MallGoodsProduct mallGoodsProduct = mallGoodsProductMapper.selectByPrimaryKey(productId);
            Integer mallGoodsProductNumber = mallGoodsProduct.getNumber();

            //获取更新后的数量
            Integer newNumber=mallGoodsProductNumber-number;
            mallGoodsProduct.setNumber(newNumber);
            mallGoodsProductMapper.updateByPrimaryKeySelective(mallGoodsProduct);


            //修改购物车表
            mallCart.setDeleted(true);
            mallCartMapper.updateByPrimaryKeySelective(mallCart);

        }


        //只用修改优惠券用户表 coupon_user
        //优惠券id一定是唯一的，根据这个去查
        MallCouponUser mallCouponUser = new MallCouponUser();

        MallCouponUserExample mallCouponUserExample=new MallCouponUserExample();
        MallCouponUserExample.Criteria couponUserExampleCriteria = mallCouponUserExample.createCriteria();
        couponUserExampleCriteria.andCouponIdEqualTo(couponId);

        couponUserExampleCriteria.andUserIdEqualTo(userId);

        mallCouponUser.setCouponId(couponId);
        mallCouponUser.setStatus(Short.parseShort("1"));//1代表已使用

        mallCouponUser.setUsedTime(date);
        mallCouponUser.setUpdateTime(date);
        mallCouponUser.setOrderId(orderId);

        mallCouponUserMapper.updateByExampleSelective(mallCouponUser,mallCouponUserExample);


        return orderId;

    }



    @Override
    public Integer cancelByWx(WxOrderIdBO wxOrderIdBO) {

        MallOrder mallOrder = mallOrderMapper.selectByPrimaryKey(wxOrderIdBO.getOrderId());
        Integer orderId=wxOrderIdBO.getOrderId();
        mallOrder.setId(orderId);
        mallOrder.setOrderStatus(102);

        Date date = new Date();
        mallOrder.setEndTime(date);
        mallOrder.setUpdateTime(date);
        int i = mallOrderMapper.updateByPrimaryKeySelective(mallOrder);

        //取消订单后还要把商品的规格库存表和优惠券的库存改回去

        //先根据orderId去OrderGoods表中取所有的productId
        MallOrderGoodsExample mallOrderGoodsExample = new MallOrderGoodsExample();
        MallOrderGoodsExample.Criteria criteria = mallOrderGoodsExample.createCriteria();
        criteria.andOrderIdEqualTo(orderId);

        List<MallOrderGoods> mallOrderGoodsList = mallOrderGoodsMapper.selectByExample(mallOrderGoodsExample);
        for (MallOrderGoods mallOrderGoods : mallOrderGoodsList) {
            Integer productId = mallOrderGoods.getProductId();
            Short orderGoodsNumber = mallOrderGoods.getNumber();

            MallGoodsProduct mallGoodsProduct = mallGoodsProductMapper.selectByPrimaryKey(productId);
            mallGoodsProduct.setUpdateTime(date);

            //取出现在的仓库数量并加上订单原本购买的
            Integer oldNumber = mallGoodsProduct.getNumber();
            mallGoodsProduct.setNumber(oldNumber+orderGoodsNumber);

            int j = mallGoodsProductMapper.updateByPrimaryKeySelective(mallGoodsProduct);

        }


        //修改coupon_user表，把原来订单用的优惠券加回去
        MallCouponUserExample mallCouponUserExample = new MallCouponUserExample();
        MallCouponUserExample.Criteria couponUserExampleCriteria = mallCouponUserExample.createCriteria();
        couponUserExampleCriteria.andOrderIdEqualTo(orderId);

        int userId = CurrentUesr.getUserId();
        couponUserExampleCriteria.andUserIdEqualTo(userId);

        List<MallCouponUser> mallCouponUsers = mallCouponUserMapper.selectByExample(mallCouponUserExample);
        //由于每个人每次只能用一个优惠券,故其实此mallCouponUsers中最多只有一个对象

        if (mallCouponUsers.size()!=0){//不等于null说明在coupon_user表中查找到了，使用了优惠券
            MallCouponUser mallCouponUser = mallCouponUsers.get(0);

            mallCouponUser.setStatus(Short.parseShort("0"));
            mallCouponUser.setUsedTime(null);//改为未使用状态，使用时间也要清零
            mallCouponUser.setUpdateTime(date);
            mallCouponUser.setOrderId(null);//改为未使用状态，订单id也要清零

            int k = mallCouponUserMapper.updateByPrimaryKeySelective(mallCouponUser);
        }



        return i;

    }

    @Override
    public Integer refundByWx(WxOrderIdBO wxOrderIdBO) {
        MallOrder mallOrder = mallOrderMapper.selectByPrimaryKey(wxOrderIdBO.getOrderId());
        Integer orderId=wxOrderIdBO.getOrderId();
        mallOrder.setId(orderId);
        mallOrder.setOrderStatus(202);

        Date date = new Date();
        mallOrder.setUpdateTime(date);

        int i = mallOrderMapper.updateByPrimaryKeySelective(mallOrder);




        //申请退款后也都要把商品的规格库存表和优惠券的库存改回去

        //先根据orderId去OrderGoods表中取所有的productId
        MallOrderGoodsExample mallOrderGoodsExample = new MallOrderGoodsExample();
        MallOrderGoodsExample.Criteria criteria = mallOrderGoodsExample.createCriteria();
        criteria.andOrderIdEqualTo(orderId);

        List<MallOrderGoods> mallOrderGoodsList = mallOrderGoodsMapper.selectByExample(mallOrderGoodsExample);
        for (MallOrderGoods mallOrderGoods : mallOrderGoodsList) {
            Integer productId = mallOrderGoods.getProductId();
            Short orderGoodsNumber = mallOrderGoods.getNumber();

            MallGoodsProduct mallGoodsProduct = mallGoodsProductMapper.selectByPrimaryKey(productId);
            mallGoodsProduct.setUpdateTime(date);

            //取出现在的仓库数量并加上订单原本购买的
            Integer oldNumber = mallGoodsProduct.getNumber();
            mallGoodsProduct.setNumber(oldNumber+orderGoodsNumber);

            int j = mallGoodsProductMapper.updateByPrimaryKeySelective(mallGoodsProduct);

        }


        //修改coupon_user表，把原来订单用的优惠券加回去
        MallCouponUserExample mallCouponUserExample = new MallCouponUserExample();
        MallCouponUserExample.Criteria couponUserExampleCriteria = mallCouponUserExample.createCriteria();
        couponUserExampleCriteria.andOrderIdEqualTo(orderId);

        int userId = CurrentUesr.getUserId();
        couponUserExampleCriteria.andUserIdEqualTo(userId);

        List<MallCouponUser> mallCouponUsers = mallCouponUserMapper.selectByExample(mallCouponUserExample);

        if (mallCouponUsers.size()!=0) {//不等于null说明在coupon_user表中查找到了，使用了优惠券
            //由于每个人每次只能用一个优惠券,故其实此mallCouponUsers中最多只有一个对象
            MallCouponUser mallCouponUser = mallCouponUsers.get(0);

            mallCouponUser.setStatus(Short.parseShort("0"));
            mallCouponUser.setUsedTime(null);//改为未使用状态，使用时间也要清零
            mallCouponUser.setUpdateTime(date);
            mallCouponUser.setOrderId(null);//改为未使用状态，订单id也要清零

            int k = mallCouponUserMapper.updateByPrimaryKeySelective(mallCouponUser);
        }


        return i;
    }


    @Override
    public Integer deleteByWx(WxOrderIdBO wxOrderIdBO) {
        MallOrder mallOrder = new MallOrder();
        mallOrder.setId(wxOrderIdBO.getOrderId());
        mallOrder.setDeleted(true);
        int i = mallOrderMapper.updateByPrimaryKeySelective(mallOrder);
        return i;
    }


    @Override
    public Integer confirmByWx(WxOrderIdBO wxOrderIdBO) {
        MallOrder mallOrder = new MallOrder();
        mallOrder.setId(wxOrderIdBO.getOrderId());
        mallOrder.setOrderStatus(401);

        Date date = new Date();
        mallOrder.setUpdateTime(date);
        mallOrder.setConfirmTime(date);
//        mallOrder.setComments();//待评价订单商品数量

        int i = mallOrderMapper.updateByPrimaryKeySelective(mallOrder);
        return i;
    }


    @Override
    public MallOrderGoods getGoodsByWx(Integer orderId, Integer goodsId) {
        MallOrderGoodsExample mallOrderGoodsExample = new MallOrderGoodsExample();
        MallOrderGoodsExample.Criteria criteria = mallOrderGoodsExample.createCriteria();

        criteria.andOrderIdEqualTo(orderId);
        criteria.andGoodsIdEqualTo(goodsId);

        List<MallOrderGoods> mallOrderGoodsList = mallOrderGoodsMapper.selectByExample(mallOrderGoodsExample);
        //集合里面其实只有一个对象
        MallOrderGoods mallOrderGoods = mallOrderGoodsList.get(0);
        return mallOrderGoods;
    }


    @Override
    public Integer commentByWx(WxOrderGoodsCommentBO wxOrderGoodsCommentBO) {

        int orderGoodsId = wxOrderGoodsCommentBO.getOrderGoodsId();
        MallOrderGoods mallOrderGoods = mallOrderGoodsMapper.selectByPrimaryKey(orderGoodsId);

        Integer orderId = mallOrderGoods.getOrderId();
        MallOrder mallOrder = mallOrderMapper.selectByPrimaryKey(orderId);


        //修改order表中的comments字段
        Short commentsNum = mallOrder.getComments();
        Integer num = commentsNum - Short.parseShort("1");
        String numString = String.valueOf(num);
        Short newNum = Short.parseShort(numString);

        mallOrder.setComments(newNum);
        mallOrderMapper.updateByPrimaryKeySelective(mallOrder);




        MallComment mallComment = new MallComment();

        mallComment.setValueId(mallOrderGoods.getGoodsId());//就是goodsId
        mallComment.setType(Byte.parseByte("3"));//这种途径评论全部设为3
        mallComment.setContent(wxOrderGoodsCommentBO.getContent());
        mallComment.setUserId(mallOrder.getUserId());
        mallComment.setHasPicture(wxOrderGoodsCommentBO.isHasPicture());

        mallComment.setPicUrls(wxOrderGoodsCommentBO.getPicUrls());
        mallComment.setStar(wxOrderGoodsCommentBO.getStar());

        Date date = new Date();
        mallComment.setAddTime(date);
        mallComment.setUpdateTime(date);
        mallComment.setDeleted(false);

        int i = mallCommentMapper.insertSelective(mallComment);
        Integer commentId = mallComment.getId();
        //还需在orderGoods表里插入commentId
        MallOrderGoods mallOrderGoods1 = new MallOrderGoods();
        mallOrderGoods1.setId(orderId);
        mallOrderGoods1.setComment(commentId);
        int j = mallOrderGoodsMapper.updateByPrimaryKeySelective(mallOrderGoods1);



        return j;
    }


}
